package com.huidu.bitrade.config.mp;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

@Component
public class MyMetaObjectHandler  implements MetaObjectHandler {

    private static final String CREATE_TIME="createTime";
    private static final String UPDATE_TIME="updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        Class<?> cls = metaObject.getOriginalObject().getClass();
        try {
            Class<?> createType = cls.getDeclaredField(CREATE_TIME).getType();
            Class<?> updateType = cls.getDeclaredField(UPDATE_TIME).getType();
            //根据名称设置属性值
            if(createType== LocalDateTime.class){
                this.setFieldValByName(CREATE_TIME,getDateTime(),metaObject);
            }else if(createType== Long.class){
                this.setFieldValByName(CREATE_TIME,getDate(),metaObject);
            }

            if(updateType== LocalDateTime.class){
                this.setFieldValByName(UPDATE_TIME,getDateTime(),metaObject);
            }else if(updateType== Long.class){
                this.setFieldValByName(UPDATE_TIME,getDate(),metaObject);
            }
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }


    //使用mp实现修改操作,这个方法会执行
    @Override
    public void updateFill(MetaObject metaObject) {
        Class<?> cls = metaObject.getOriginalObject().getClass();
        try {
            Class<?> updateType = cls.getDeclaredField(UPDATE_TIME).getType();
            if(updateType== LocalDateTime.class){
                this.setFieldValByName(UPDATE_TIME,getDateTime(),metaObject);
            }else if(updateType== Long.class){
                this.setFieldValByName(UPDATE_TIME,getDate(),metaObject);
            }
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    private LocalDateTime getDateTime(){
        return LocalDateTime.now();
    }

    private Long getDate(){
        return new Date().getTime();
    }
}
